/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler;

import com.jme.renderer.Renderer;
import com.jmex.bui.BComponent;
import com.jmex.bui.BRootNode;
import com.jmex.bui.event.BEvent;
import org.lwjgl.opengl.GL11;

import java.util.LinkedList;
import java.util.List;

public abstract class BPRootNode extends BRootNode {

    private List< Pair< BEvent, BComponent > > events = new LinkedList< Pair< BEvent, BComponent > >();

    boolean mouseMove = false;
    int mouseX = 0;
    int mouseY = 0;

    public BPRootNode() {
        super();
    }

    @Override
    public long getTickStamp() {
        return System.currentTimeMillis();
    }

    // documentation inherited
    public void rootInvalidated(BComponent root) {
        root.validate();
    }

    protected void addEvent(BComponent target, BEvent event) {

        events.add( new Pair< BEvent, BComponent >( event, target ) );
    }

    protected void addMouseMove(int x, int y) {
        mouseMove = true;
        mouseX = x;
        mouseY = y;
    }

    public void dispatchEvents() {

        if (mouseMove) {
            mouseDidMove(mouseX, mouseY);
            mouseMove = false;
        }

        if( !events.isEmpty() ) {
            for( Pair< BEvent, BComponent > event : events ) {
               dispatchEvent( event.second, event.first );
            }
            events.clear();
        }
    }

    public void draw( Renderer renderer ) {
        GL11.glScalef( getLocalScale().getX(), getLocalScale().getY(), 1.0f );
        super.draw( renderer );
    }

    public static class Pair<T, S>
    {
        public final T first;
        public final S second;

        public Pair(T f, S s)
        {
            first = f;
            second = s;
        }

        public String toString()
        {
            return "(" + first + ", " + second + ")";
        }
    }
}


